const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const chatMessages = document.getElementById('chatMessages');
const joinRoomBtn = document.getElementById('joinRoomBtn');
const createRoomBtn = document.getElementById('createRoomBtn');
const roomInput = document.getElementById('roomInput');
let roomId = roomInput.value;
let webSocket;
const isOnline = false;
const host = window.location.host;
const connectWebSocketUrl = 'ws://'+ host +'/game/websocket/message';
// 创建WebSocket连接
let currentUser = '游客'; // 假设当前用户是user1
function clickSendButton() {
    const messageText = messageInput.value.trim();
    if (messageText) {
        const date = new Date().getTime();
        buildTextWebSocketMessage(messageText, date);
        // sendMessage(currentUser, messageText, date);
    }
}

function buildTextWebSocketMessage(messageText, createTime) {
    return buildWebSocketMessage(messageText, 'ROOM_TEXT', createTime);
}

function buildWebSocketMessage(textMessage, type, createTime) {
    let isOnline = false;
    const message = {
        messageId: '',
        messageType: type,
        message: textMessage,
        from: currentUser,
        to: roomInput.value,
        createTime: createTime,
        status: 0
    };
    if (webSocket) {
        const sendMessage = JSON.stringify(message);
        console.log("发送了websocket消息");
        console.log(sendMessage);
        webSocket.send(sendMessage);
        isOnline = true;
    }
    return isOnline;
}

function sendMessage(user, messageText, createTime) {
    if (!createTime) {
        createTime = new Date().getTime();
    }
    // 创建一个新的消息元素
    const messageElement = document.createElement('div');
    messageElement.classList.add('message');
    // 创建消息头部（发送人和时间戳）
    const messageHeader = document.createElement('div');
    messageHeader.classList.add('message-header');
    messageHeader.innerHTML = `<span>${user}</span><span class="message-timestamp">${formatDate(createTime)}</span>`;
    // 创建消息体
    const messageBody = document.createElement('div');
    messageBody.classList.add('message-body');
    if (user === currentUser) {
        messageBody.classList.add("sent");
    }
    messageBody.textContent = messageText;
    // 将消息头部和消息体添加到消息元素中
    messageElement.appendChild(messageHeader);
    messageElement.appendChild(messageBody);
    // 将消息添加到聊天历史中
    const chatHistory = document.getElementById('chatHistory');
    chatHistory.appendChild(messageElement);
    // 清空输入框并滚动到底部
    messageInput.value = '';
    chatHistory.scrollTop = chatHistory.scrollHeight;
}

function formatDate(datetime) {
    const date = new Date(datetime);
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds()
    // 确保小时、分钟和秒都是两位数
    hours = hours < 10 ? "0" + hours : hours;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    // 组合成 HH:mm:ss 格式
    return hours + ":" + minutes + ":" + seconds;
}

sendBtn.addEventListener('click', clickSendButton);
// 监听textarea的keydown事件，按下回车键时发送消息
messageInput.addEventListener('keydown', function (event) {
    if (event.key === 'Enter' && !event.shiftKey) { // 检查是否按下回车键且没有同时按下Shift键
        event.preventDefault(); // 阻止默认的换行行为
        clickSendButton(); // 发送消息
    }
});
joinRoomBtn.addEventListener('click', function () {
    connectSocket(function () {
        roomId = roomInput.value;
        buildWebSocketMessage(roomId, "ROOM_JOIN", new Date().getTime());
    });
});
createRoomBtn.addEventListener('click', function () {
    connectSocket(function () {
        buildWebSocketMessage("", "ROOM_CREATE", new Date().getTime())
    });
});

function connectSocket(callBack) {
    if (webSocket) {
        return;
    }
    webSocket = new WebSocket(connectWebSocketUrl);

    // 连接打开时的事件处理程序
    webSocket.onopen = function (event) {
        console.log('WebSocket connection opened.');
        sendMessage("系统", "聊天服务器已连接");
        if (callBack && callBack instanceof Function) {
            callBack();
        }
        // 可以在这里发送初始消息到服务器（可选）
        // webSocket.send('Your initial message here');
    };
// 收到消息时的事件处理程序
    webSocket.onmessage = function (event) {
        // event.data 包含服务器发送的消息内容（这里是JSON字符串）
        const message = event.data;
        console.log('消息接收:');
        // 解析JSON字符串为JavaScript对象
        const parsedMessage = JSON.parse(message);
        console.log(parsedMessage);
        // 根据消息类型执行相应的操作
        switch (parsedMessage.messageType) {
            case 'ROOM_TEXT':
                // 处理文本消息
                // displayTextMessage(parsedMessage.content, parsedMessage.senderName, parsedMessage.timestamp);
                sendMessage(parsedMessage.from, parsedMessage.message, parsedMessage.createTime);
                break;
            case 'ROOM_CREATE':
                currentUser = parsedMessage.from;
                roomInput.value = parsedMessage.to;
                sendMessage("系统", "已创建房间,当前房间号为" + parsedMessage.to, parsedMessage.createTime);
                break;
            case 'ROOM_JOIN':
                currentUser = parsedMessage.from;
                roomInput.value = parsedMessage.to;
                sendMessage("系统", "已加入房间,当前房间号为" + parsedMessage.to, parsedMessage.createTime);
                break;
            case 'WUZIQI':
                // 处理五子棋小游戏
                handleWuZiQi(parsedMessage.from, parsedMessage.message, parsedMessage.createTime);
                // displayImageMessage(parsedMessage.content, parsedMessage.senderName, parsedMessage.timestamp);
                break;
            default:
                sendMessage("系统", "接收到未知消息，暂无法查看");
                break;
        }
    };

// 连接关闭时的事件处理程序
    webSocket.onclose = function (event) {
        console.log('WebSocket connection closed.');
        sendMessage("系统", "聊天服务器已关闭");
    };

// 发生错误时的事件处理程序
    webSocket.onerror = function (event) {
        console.error('WebSocket error:', event);
        sendMessage("系统", "聊天服务器出现错误,正在重连");
        connectSocket();
    };

}


function handleWuZiQi(from, messageString) {
    const message = JSON.parse(messageString);
    console.log("五子棋");
    console.log(message);
    switch (message.type) {
        case 'READY':
        case 'JOIN_SPECTOR':
        case 'JOIN_ROOM':
        case 'JOIN_USER':
            // handleReady(message);
            updateRoomInfo(message.value)
            break;
        case 'LUOZI':
            handleLuozi(message);
            break;
        case 'HUIQI':
            handleHuiqi(from);
            break;
        case 'START':
            startGame(message.value);
            break;
        case 'WIN':
            handleWin(message);
            break;
        case 'RESET':
            resetGame(message.value);
            break;
        case 'ERROR':
            alert(message.otherMessage);
            break;
        // case 'HUIQI':
        //     break;
        // case 'HUIQI':
        //     break;
        // case 'HUIQI':
        //     break;
    }
    // clickReady();
}

function buildWuZiQiWebsocketMessage(messageValue, createdTime) {
    if(!createdTime){
        createdTime = new Date().getTime();
    }
    const message = {
        messageId: '',
        messageType: 'WUZIQI',
        message: messageValue,
        from: currentUser,
        to: roomInput.value,
        createTime: createdTime,
        status: 0
    };
    webSocket.send(JSON.stringify(message));
}